<template>
  <div class='container'>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
       <el-form-item label="活动名称" prop="title">
          <el-input v-model="ruleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleBody" >
          <div>
              <editor ref="editorOne" v-model="detail"  @change="change"></editor>
          </div>
        </el-form-item>
        <el-form-item label="视频地址" prop="videoURL">
          <el-input v-model="ruleForm.videoURL"></el-input>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="submitArticle">确定</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
import editor from '../components/editor'

import { add, detail, update } from '@/api/hmmm/articles'

export default {
  name: 'articles-add',
  components: {
    editor
  },
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    articlePrev: {
      type: Object
    }
  },
  data () {
    return {
      // 表单数据
      ruleForm: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      // 表单规则
      rules: {
        title: [{ required: true, message: '请输入文章名称', trigger: 'blur' }],
        articleBody: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
      },
      detail: ''
    }
  },
  created () {
    this.getArticle()
  },
  methods: {
    // 监听富文本编辑器输入内容
    change () {
      if (this.timeout) {
        clearTimeout(this.timeout)
      }
      this.timeout = setTimeout(() => {
        this.ruleForm.articleBody = this.detail
      }, 500)
    },

    // 提交文章
    submitArticle () {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return this.$message.error('数据不能为空')

        this.isEdit ? this.editArticle() : this.addArticle()

        this.ruleForm = {
          title: '',
          articleBody: '',
          videoURL: ''
        }

        this.detail = ''

        this.$emit('close')
      })
    },

    // 取消关闭弹窗
    close () {
      this.ruleForm = {
        title: '',
        articleBody: '',
        videoURL: ''
      }

      this.$emit('close')
    },

    // 获取文章数据
    async getArticle () {
      if (this.isEdit) {
        console.log(this.articlePrev)
        const res = await detail(this.articlePrev)
        console.log(res)

        this.ruleForm = res.data

        this.detail = res.data.articleBody
      }
    },

    // 添加文章
    async addArticle () {
      await add(this.ruleForm) // 返回值是当前添加文章的id

      this.$message.success('添加文章成功')
    },

    // 编辑文章
    async editArticle () {
      const res = await update(this.ruleForm)

      if (res.data.success) {
        this.$message.success('编辑文章成功')
      }
    }
  }

}
</script>

<style scoped lang='less'>

</style>
